package com.milk.servlet;

import com.milk.Dao.OrdersDao;
import com.milk.entity.Orders;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class OrderManagementServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取操作类型
        String action = request.getPathInfo();
        if (action == null || action.equals("/")) {
            action = "/list"; // 默认操作是列出所有订单
        }

        switch (action) {
            case "/add":
                showAddOrderForm(request, response);
                break;
            case "/edit":
                showEditOrderForm(request, response);
                break;
            case "/delete":
                deleteOrder(request, response);
                break;
            case "/search":
                searchOrder(request, response);
                break;
            default:
                listAllOrders(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取操作类型
        String action = request.getPathInfo();
        if (action == null || action.equals("/")) {
            action = "/list"; // 默认操作是列出所有订单
        }

        switch (action) {
            case "/add":
                addOrder(request, response);
                break;
            case "/update":
                updateOrderStatus(request, response);
                break;
            default:
                // 处理其他不支持的POST请求
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }

    private void listAllOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询所有订单信息
        List<Orders> orders = OrdersDao.findAll();
        request.setAttribute("orders", orders);

        // 转发到订单列表页面（假设为order_management.jsp）
        request.getRequestDispatcher("/order_management.jsp").forward(request, response);
    }

    private void showAddOrderForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 转发到添加订单表单页面
        request.getRequestDispatcher("/add_order_form.jsp").forward(request, response);
    }

    private void addOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取订单信息参数
        String userName = request.getParameter("userName");
        String contactPhone = request.getParameter("contactPhone");
        String timeStr = request.getParameter("orderTime");
        Date orderTime = null;
        try {
            orderTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse(timeStr);
        } catch (ParseException e) {
            // 时间格式错误，返回错误信息
            response.sendRedirect(request.getContextPath() + "/orders/add?error=time");
            return;
        }
        String status = request.getParameter("status");
        String drinkIds = request.getParameter("drinkIds");

        // 创建Orders对象
        Orders order = new Orders();
        order.setUserName(userName);
        order.setContactPhone(contactPhone);
        order.setOrderTime(orderTime);
        order.setStatus(status);
        order.setDrinkIds(drinkIds);

        // 调用OrdersDao的方法添加订单
        int result = OrdersDao.add(order);
        if (result > 0) {
            // 添加成功，重定向到订单列表页面
            response.sendRedirect(request.getContextPath() + "/orders");
        } else {
            // 添加失败，返回错误信息
            response.sendRedirect(request.getContextPath() + "/orders/add?error=add");
        }
    }

    private void showEditOrderForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取要修改的订单ID
        int id = Integer.parseInt(request.getParameter("id"));

        // 根据ID查询订单信息
        Orders order = OrdersDao.findById(id);
        if (order != null) {
            request.setAttribute("order", order);
            // 转发到修改订单表单页面
            request.getRequestDispatcher("/edit_order_form.jsp").forward(request, response);
        } else {
            // 未找到对应的订单，返回错误信息
            response.sendRedirect(request.getContextPath() + "/orders?error=notfound");
        }
    }

    private void updateOrderStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取订单ID和新状态参数
        int orderId = Integer.parseInt(request.getParameter("id"));
        String newStatus = request.getParameter("status");

        // 检查 newStatus 是否为空
        if (newStatus == null || newStatus.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/orders/edit?id=" + orderId + "&error=status");
            return;
        }

        // 调用 OrdersDao 的方法修改订单状态
        int result = OrdersDao.updateStatus(orderId, newStatus);
        if (result > 0) {
            // 修改成功，查询更新后的订单信息
            Orders updatedOrder = OrdersDao.findById(orderId);
            if (updatedOrder != null) {
                // 将更新后的订单信息设置为请求属性
                request.setAttribute("updatedOrder", updatedOrder);
                // 转发到显示结果的 JSP 页面
                request.getRequestDispatcher("/update_result.jsp").forward(request, response);
            } else {
                // 未找到更新后的订单信息，返回错误信息
                response.sendRedirect(request.getContextPath() + "/orders?error=notfound");
            }
        } else {
            // 修改失败，返回错误信息
            response.sendRedirect(request.getContextPath() + "/orders/edit?id=" + orderId + "&error=update");
        }
    }

    private void deleteOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取要删除的订单ID
        int orderId = Integer.parseInt(request.getParameter("id"));

        // 调用OrdersDao的方法删除订单
        int result = OrdersDao.deleteById(orderId);
        if (result > 0) {
            // 删除成功，重定向到订单列表页面
            response.sendRedirect(request.getContextPath() + "/orders");
        } else {
            // 删除失败，返回错误信息
            response.sendRedirect(request.getContextPath() + "/orders?error=delete");
        }
    }

    private void searchOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取搜索关键字
        String userName = request.getParameter("searchUserName");

        // 检查 userName 是否为空
        if (userName == null || userName.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/orders?error=search");
            return;
        }

        // 调用OrdersDao的方法进行模糊搜索
        List<Orders> orders = OrdersDao.searchByUserName(userName);

        request.setAttribute("orders", orders);

        // 转发到订单列表页面（假设为order_management.jsp）
        request.getRequestDispatcher("/order_management.jsp").forward(request, response);
    }
}